package listbyorder.access001_100.test10;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/6 14:32
 */
public class Solution2 {

    // 方法二： 暴力递归改动态规划
    public boolean isMatch(String s, String p) {
        int cs = s.length();
        int cp = p.length();
        if (cp == 0) return cs == 0;
        boolean[][] dp = new boolean[cs + 1][cp + 1];
        for (int i = 0; i <= cs; i++) {
            for (int j = 0; j <= cp; j++) {
                if (j == 0) {
                    dp[i][j] = i == 0;
                } else if (i == 0) {
                    if (p.charAt(j - 1) == '*') {
                        dp[i][j] = j > 1 && dp[i][j - 2];
                    }
                } else if (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '.') {
                    dp[i][j] = dp[i - 1][j - 1];
                } else if (p.charAt(j - 1) == '*') {
                    if (j > 1 && (p.charAt(j - 2) != s.charAt(i - 1) && p.charAt(j - 2) != '.')) {
                        dp[i][j] = dp[i][j - 2];
                    } else if (j > 1 && (p.charAt(j - 2) == s.charAt(i - 1) || p.charAt(j - 2) == '.')) {
                        dp[i][j] = dp[i - 1][j] || dp[i][j - 1] || dp[i][j - 2];
                    }
                }
            }
        }
        return dp[cs][cp];
    }
}
